package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    List<User> list=new ArrayList<>();
    public List<User> findAll(){
        System.out.println("查询所有数据");
        //1.加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取连接
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc","root","1234");
            if (connection!=null){
                System.out.println("连接成功");
            }
            //3.写sql
            String sql = "select * from user";
            //4.预编译sql
            PreparedStatement preparedStatement= connection.prepareStatement(sql);
            //5有参数设置参数

            //6执行sql
            ResultSet resultSet=preparedStatement.executeQuery();
            //7遍历结果集
            while(resultSet.next()){
                User user=new User();
                user.setId(resultSet.getInt("id"));
                user.setName(resultSet.getString("name"));
                user.setPass(resultSet.getString("pass"));
                list.add(user);
            }
            return list;
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
